package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.properties.TaskConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.AttendAuditMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyWxMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.AttendAuditDdSupervisorParam;
import cn.stylefeng.guns.sys.modular.system.model.params.AttendAuditManagerSetParam;
import cn.stylefeng.guns.sys.modular.system.model.params.AttendAuditParam;
import cn.stylefeng.guns.sys.modular.system.model.result.AttendAuditBtyAreaAuditStatusResult;
import cn.stylefeng.guns.sys.modular.system.model.result.AttendAuditManagerSetResult;
import cn.stylefeng.guns.sys.modular.system.model.result.AttendAuditResult;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.guns.sys.modular.system.db6.entity.SysDict;
import cn.stylefeng.guns.sys.modular.system.db6.service.SysDictService;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.AttendAuditStatusEnum;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.aspectj.weaver.Iterators;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 出勤_督导审核店长表 服务实现类
 * </p>
 *
 * @author wjk
 * @since 2021-09-14
 */
@Service
public class AttendAuditServiceImpl extends ServiceImpl<AttendAuditMapper, AttendAudit> implements AttendAuditService {


    @Resource
    private AttendAuditBtyAreaService attendAuditBtyAreaService;

    @Resource
    private AttendAuditBtyArchivesService attendAuditBtyArchivesService;

    @Resource
    private AttendEmployeeMonthService attendEmployeeMonthService;

    @Resource
    private SysDictService sysDictService;

    @Resource
    private AttendDismissedService attendDismissedService;

    @Autowired
    private PushMsgService pushMsgService;

    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;

    @Resource
    private BtyWxMapper btyWxMapper;

    @Resource
    private TaskConfig taskConfig;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");

    SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");

    SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public void add(AttendAuditParam param){
        AttendAudit entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(AttendAuditParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(AttendAuditParam param){
        AttendAudit oldEntity = getOldEntity(param);
        AttendAudit newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public AttendAuditResult findBySpec(AttendAuditParam param){
        return null;
    }

    @Override
    public List<AttendAuditResult> findListBySpec(AttendAuditParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(AttendAuditParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 根据店长店电话创建一条考勤审核的记录
     *
     * @author wjk
     * @Date 2021-09-17
     */
    @Override
    public AttendAudit addAttendAuditByDzPhone(String account,String attendMonth) {
        //根据店长信息获取店的信息；
        AttendAuditBtyArea  shopInfo = this.attendAuditBtyAreaService.getShopInfoByDzPhone(account);
        //根据督导的名字获取督导的信息；
        AttendAuditBtyArchives  ddInfo =  this.attendAuditBtyArchivesService.getDdInfoByName(shopInfo.getDd());
        //根据店长电话获取店长的信息；
         AttendAuditBtyArchives attendAuditBtyArchivesdd = attendAuditBtyArchivesService.getOneByPhone(account);

        //提交月份；
        String submitMonth = sdf.format(new Date());
        //查询是否有提交的记录了，有提交记录则返回已经提交的记录
        AttendAudit attendAuditOld = this.getById(Long.valueOf(attendMonth+attendAuditBtyArchivesdd.getId()));
        if(attendAuditOld == null){
            AttendAudit attendAudit = new AttendAudit();

            //将id设置成月份加店长的id进行提交
            attendAudit.setId(Long.valueOf(attendMonth+attendAuditBtyArchivesdd.getId()));

            attendAudit.setSubmitMonth(submitMonth);

            attendAudit.setAttendMonth(attendMonth);

            attendAudit.setDdSupervisorId(Long.valueOf(ddInfo.getId()));
            attendAudit.setDdSupervisorPhone(ddInfo.getTel());
            attendAudit.setDdSupervisorName(ddInfo.getXm());

            attendAudit.setManagerId(Long.valueOf(attendAuditBtyArchivesdd.getId()));
            attendAudit.setManagerPhone(attendAuditBtyArchivesdd.getTel());
            attendAudit.setManagerName(attendAuditBtyArchivesdd.getXm());

            attendAudit.setAuditStatus(AttendAuditStatusEnum.NOT_SUBMIT.getCode());

            attendAudit.setDm(shopInfo.getDm());
            attendAudit.setBtyAreaBh(shopInfo.getBh());
            attendAudit.setBtyAreaId(shopInfo.getId());

            boolean falg = this.save(attendAudit);

            if(falg){
                return attendAudit;
            }else{
                return new AttendAudit();
            }
        }else{
            return attendAuditOld;
        }
    }
    /**
     *（店长考勤修改页面）店长提交审核，先验证手机号，在验证aaId，在验证旗下有没有数据所有都符合要求
     * @param account
     * @param aaId
     * @return
     * @author wjk
     * @Date 2021-11-10
     */
    @Override
    public Map<String,String> managerSubmitAuditByPhoneAndIdValidation(String account, String aaId){
        Map<String,String> map = new HashMap<String,String>();
        map.put("flag","false");
        map.put("message","");
        AttendAuditParam param  = new AttendAuditParam();
        param.setId(Long.valueOf(aaId));
        param.setAuditStatus(AttendAuditStatusEnum.SUBMIT_AUDIT.getCode());
        AttendAudit oldEntity = getOldEntity(param);
        if(ToolUtil.isEmpty(oldEntity)){
            map.put("message","未找到考勤信息");
            return map;
        }
        AttendAuditManagerSetParam attendAuditManagerSetParam = new AttendAuditManagerSetParam();
        attendAuditManagerSetParam.setAccount(account);
        boolean flag = true;
        List<AttendAuditManagerSetResult> list =  this.attendEmployeeMonthService.getEmployeeListMonthByManagerSetParam(attendAuditManagerSetParam);
        for(int i = 0;i<list.size();i++){
            AttendAuditManagerSetResult attendAuditManagerSetResult = list.get(i);


            AttendAuditManagerSetResult attendAuditManagerSetResultNew = this.attendEmployeeMonthService.calculateEmployeeSalary(attendAuditManagerSetResult,account);
            //（判断考勤天数和公休天数是否为null或者0，判断gz和gw工资是否共同为零），如果其中一个值未空则，进行清空当条记录的应发工资数据
            //职位为空
            //考勤天数为空

            if(ToolUtil.isEmpty(attendAuditManagerSetResultNew.getZw())
                    ||ToolUtil.isEmpty(attendAuditManagerSetResultNew.getAttendanceDays())){
                attendAuditManagerSetResultNew.setShouldPay(null);
            }
            //基本工资
            BigDecimal gz = attendAuditManagerSetResult.getGz();
            //岗位工资
            BigDecimal gw = attendAuditManagerSetResult.getGw();
            //gz和gw共同为空
            if(gz.compareTo(BigDecimal.ZERO)==0&&gw.compareTo(BigDecimal.ZERO)==0){
                attendAuditManagerSetResultNew.setShouldPay(null);
            }

            if(ToolUtil.isEmpty(attendAuditManagerSetResult.getZw())){
                map.put("message"," "+attendAuditManagerSetResult.getXm() +"个人信息为空，请去编辑员工信息");
                flag = false;
                break;
            }
            //判断职位为督导的应发是否发工资不能为不发 attendAuditManagerSetResult.getPayWage()!=1 并且应发工资不能为0
            if(ToolUtil.isNotEmpty(attendAuditManagerSetResult.getZw())&&attendAuditManagerSetResult.getZw().equals("督导")){
                if(ToolUtil.isNotEmpty(attendAuditManagerSetResult.getPayWage())&&attendAuditManagerSetResult.getPayWage().equals("1")){
                    map.put("message","督导 "+attendAuditManagerSetResult.getXm() +"必须发工资，并且应发工资不能为0");
                    flag = false;
                    break;
                }
                if(ToolUtil.isEmpty(attendAuditManagerSetResult.getShouldPay())||attendAuditManagerSetResult.getShouldPay().compareTo(BigDecimal.ZERO)==0){
                    map.put("message","督导 "+attendAuditManagerSetResult.getXm() +"必须发工资，并且应发工资不能为0");
                    flag = false;
                    break;
                }
            }


            //若应发工资，不为空，并且应发工资为应发，则判断工资不能为0，并且等与计算工资
            if(ToolUtil.isEmpty(attendAuditManagerSetResult.getPayWage())||(ToolUtil.isNotEmpty(attendAuditManagerSetResult.getPayWage())&&attendAuditManagerSetResult.getPayWage().equals("0"))){
                //应发工资不能为空
                if(ToolUtil.isEmpty(attendAuditManagerSetResult.getShouldPay())){
                    map.put("message","员工 "+attendAuditManagerSetResult.getXm() +"应发工资，但应发工资为空，请输入考勤天数，计算应发工资");
                    flag = false;
                    break;
                }
                //应发工资不，或者0
                if(attendAuditManagerSetResult.getShouldPay().compareTo(BigDecimal.ZERO)==0){
                    map.put("message","员工 "+attendAuditManagerSetResult.getXm() +"应发工资，但应发工资为0，请输入考勤天数，计算应发工资");
                    flag = false;
                    break;
                }
                //计算后的应发工资等于空
                if(ToolUtil.isEmpty(attendAuditManagerSetResultNew.getShouldPay())){
                    map.put("message","员工 "+attendAuditManagerSetResult.getXm() +"应发工资，与计算值不符，请确定是否输入了正确的工资或者考勤天数");
                    flag = false;
                    break;
                }
                //计算后的应发工资不等于空
                if(ToolUtil.isNotEmpty(attendAuditManagerSetResultNew.getShouldPay())){
                    if(attendAuditManagerSetResult.getShouldPay().compareTo(attendAuditManagerSetResultNew.getShouldPay())==0){

                    }else {
                        map.put("message","员工 "+attendAuditManagerSetResult.getXm() +"应发工资，与计算值不符，请确定是否输入了正确的工资或者考勤天数");
                        flag = false;
                        break;
                    }
                }else{
                    //不发工资的情况下发工资应该等于0
                    //应发工资不，或者0
                    if(attendAuditManagerSetResult.getShouldPay().compareTo(BigDecimal.ZERO)==0){

                    }else {
                        map.put("message","员工 "+attendAuditManagerSetResult.getXm() +"不发工资，但其应发工资计算有值，请确认是否输入了正确的工资或者考勤天数");
                        flag = false;
                        break;
                    }
                }

            }
        }
        //若判断失败了则返回
        if(flag == false){
            map.put("flag","false");
        }else{
            map.put("flag","true");
        }

        return map;
    }
    /**
     * （店长考勤修改页面）店长提交该审核信息
     *
     *
     * @author wjk
     * @Date 2021-09-17
     */
    @Override
    public boolean managerSubmitAuditByPhoneAndId(String account, String aaId) {
        //id不能为空
        if(ToolUtil.isEmpty(aaId)){
            return false;
        }
        AttendAuditParam param  = new AttendAuditParam();
        param.setId(Long.valueOf(aaId));
        param.setAuditStatus(AttendAuditStatusEnum.SUBMIT_AUDIT.getCode());
        AttendAudit oldEntity = getOldEntity(param);
        if(ToolUtil.isEmpty(oldEntity)){
            return false;
        }
        //获取到旧的提交信息之后验证一下这个店长的电话，之后进行提交，返回提交信息
        if(oldEntity.getManagerPhone().equals(account)){
            AttendAudit newEntity = getEntity(param);
            ToolUtil.copyProperties(newEntity, oldEntity);

            //修改若有新员工，则更改新员工状态,为提交状态
            int size = attendEmployeeMonthService.newEmployeeSubmitAudit(aaId);

            //修改若有驳回状态的信息，修改驳回信息为历史记录
            int sizeAttendDismissed = attendDismissedService.updateDismissedStateByAaId(aaId);

            return this.updateById(newEntity);
        }else{
            return false;
        }
    }

    /**
     * （督导审核页面）督导审核，通过；
     * @author wjk
     * @Date 2021-09-18
     *
     */
    @Override
    public boolean setAttendAuditApproveByEmployeeList(List<AttendAuditManagerSetResult> param,String account) {

        boolean listFalg = validationList(param,account);
        if(listFalg){
            List<Long> aaIdListWithoutDuplicates = getAaIdListWithoutDuplicates(param);
            //更新审核表的状态 (audit_status:(1 or 3) to 2)
            int approveFalg = this.baseMapper.setAttendAuditApproveByAaId(aaIdListWithoutDuplicates);
            //更新对新员工的状态(synchronous_status:(2 or 4) to 3)
            int newEmployeeFalg = this.attendEmployeeMonthService.newEmployeeApprove(param,account);
            if(approveFalg == 0 ){
                listFalg = false;
            }
        }

        return listFalg;
    }

    /**
     * （督导审核页面）督导审核，驳回；
     * @author wjk
     * @Date 2021-09-18
     */

    @Override
    public boolean setAttendAuditBackByEmployeeList(List<AttendAuditManagerSetResult> param, String account) {
        boolean listFalg = validationList(param,account);
        if(listFalg){
            List<Long> aaIdListWithoutDuplicates = getAaIdListWithoutDuplicates(param);

            //更新审核表的状态 (audit_status:1 to 3 )
            int backFalg = this.baseMapper.setAttendAuditBackByAaId(aaIdListWithoutDuplicates);

            //更新对新员工的状态(synchronous_status: 2 to 4)
            int newEmployeeFalg = this.attendEmployeeMonthService.newEmployeeBack(param,account);
            if(backFalg == 0 ){
                listFalg = false;
            }
            //增加驳回员工的驳回信息
//            AttendDismissedParam attendDismissedParam = new AttendDismissedParam();
//            attendDismissedService.add(attendDismissedParam);
            int size = attendDismissedService.addList(param,account);
            //获取消息推送的不重复店名
            List<Map<String,String>> PushMsgList = getPushMsgListWithoutDuplicates(param);

            //提交推送不同的店铺
            for(Map<String,String> mapShop:PushMsgList){
                //消息推送畅聊
                //System.out.println(mapShop.toString());
                pushMsgService.attendAuditPushMsgToIM(mapShop.get("shopName"),mapShop.get("dzMobile"),mapShop.get("msgTime"));
                setAttendAuditBackByEmployeeListToWeChat(mapShop.get("shopName"),mapShop.get("dzMobile"),mapShop.get("msgTime"));
            }
        }

        //attendAuditPushMsgToIM(String ShopName, String dzMobile,String msgTime);
        return listFalg;
    }

    /**
     * （督导审核页面）督导审核，驳回，推送店长
     * @author wjk
     * @Date 2021-11-10
     */
    private void setAttendAuditBackByEmployeeListToWeChat(String ShopName, String dzMobile,String msgTime){
        String now = DateUtil.getNow();//当前时间
        //公众号驳回提醒：“上海崇明万达店”2021年9月考勤被督导驳回，请及时进入小妖APP，点击录入考勤菜单，在驳回列表修改并重新提交考勤
        String data =" \"" + ShopName+"\"，"+msgTime+"考勤被督导驳回，请及时进入小妖APP，点击[录入考勤]菜单，在驳回列表修改并重新提交考勤";
        JSONObject tempObj = weChatSendTempMsgService.setTempParam(ShopName, null, "考勤提醒", "考勤提醒", now, data);
        if (taskConfig.getRun().equals("y")) {

        } else {
            dzMobile = "17686420611";
        }
        //获取受让方openid
        User user = btyWxMapper.getOpenId(dzMobile);
        String[] openid = null;
        if (ToolUtil.isNotEmpty(user)) {
            openid = new String[]{user.getOpenid()};
        }

        weChatSendTempMsgService.sendmsg(openid, null, tempObj);
    }
    /**
     * 根据店长店电话返回店长当月的一条考勤审核的记录
     *
     * @author wjk
     * @Date 2021-09-22
     */

    @Override
    public AttendAudit getAttendAuditByDzPhone(String account) {
        LambdaQueryWrapper<AttendAudit> queryWrapper = new LambdaQueryWrapper<AttendAudit>();
        queryWrapper.eq(AttendAudit::getManagerPhone,account);

        //获取相关月份的考勤信息
        Map<String,String> map = attendAuditBtyArchivesService.intoAttendEmployeeMonthListValidationParam(null,null);
        String attendMonth = map.get("attendMonth").replaceAll("-","");
        queryWrapper.eq(AttendAudit::getAttendMonth,attendMonth);
        List<AttendAudit> list = this.baseMapper.selectList(queryWrapper);
        AttendAudit attendAudit = new AttendAudit();
        if(list.size()>0){
            attendAudit = list.get(0);
        }
        return attendAudit;
    }

    /**
     * 根据督导的手机号，和提交月份或者考勤月份，获得该月的考勤提交门店统计
     *
     * @author wjk
     * @Date 2021-09-23
     */
    @Override
    public Map<String, String> getStatusCountByDd(AttendAuditDdSupervisorParam param) {
        Map<String, String> statusMap = this.baseMapper.getStatusCountByDd(param);
        return statusMap;
    }
    /**
     * 根据大店长的手机号，和提交月份或者考勤月份，获得该月的考勤提交门店统计
     *
     * @author wjk
     * @Date 2021-10-19
     */
    @Override
    public Map<String,String> getStatusCountByDdz(AttendAuditDdSupervisorParam param){
        Map<String, String> statusMap = this.baseMapper.getStatusCountByDdz(param);
        return statusMap;
    }
    /**
     * 根据yyjl的手机号，和提交月份或者考勤月份，获得该月的考勤提交门店统计
     * @param param
     * @return
     */
    @Override
    public Map<String, String> getStatusCountByYyjl(AttendAuditDdSupervisorParam param) {
        Map<String, String> statusMap = this.baseMapper.getStatusCountByYyjl(param);
        return statusMap;
    }


    /**
     * （督导审核界面）返回服务器当前应该审核的考勤月份和应该提交的月份
     * @author wjk
     * @Date 2021-09-29
     */
    @Override
    public Map<String, String> getAttendMonth() {
        Map<String, String> map = new HashMap<String, String>();
        Map<String,String> mapParam = attendAuditBtyArchivesService.intoAttendEmployeeMonthListValidationParam(null, null);
        String attendMonth = mapParam.get("attendMonth");
        StringBuffer sb = new StringBuffer(attendMonth);
        sb.insert(4, "-");
        map.put("attendMonth",sb.toString());
        //map.put("attendMonth",sdf2.format(this.attendEmployeeMonthService.calculateMonth(new Date(),-1)));
        //map.put("submitMonth",sdf2.format(new Date()));
        map.put("day",sdfDay.format(new Date()));
        map.put("time",sdfTime.format(new Date()));
        return map;
    }
    /**
     * （店长创建考勤页面）创建考勤界面，返回是否允许创建考勤信息
     * @author wjk
     * @Date 2021-09-30
     */
    @Override
    public Map<String,String> getCreateAttendButton(){
        Map<String, String> map = new HashMap<String, String>();
        map.put("buttonInfo","不允许创建考勤");
        Date date = new Date();
        SimpleDateFormat daySdf = new SimpleDateFormat("dd");

        SimpleDateFormat monthSdf = new SimpleDateFormat("MM");

        String day = daySdf.format(date);
        String lastMonth = monthSdf.format(this.attendEmployeeMonthService.calculateMonth(date,-1));
        String month = monthSdf.format(this.attendEmployeeMonthService.calculateMonth(date,0));

        SimpleDateFormat yyyyMMddSdf = new SimpleDateFormat("yyyy-MM-dd");

        String days = "";
        //由于创建考勤，只允许1号和2号，因此限制本次考勤  ATTEND_AUDIT
        //sysDictService.
        List<SysDict> listSysDict = this.sysDictService.getSysDictAttendAudit();

        String buttonValid = "1";//禁止创建考勤
        for(int i = 0;i<listSysDict.size();i++){
            SysDict sysDict = listSysDict.get(i);
            if(ToolUtil.isNotEmpty(sysDict)&&ToolUtil.isNotEmpty(sysDict.getCode())){
                String code = sysDict.getCode();
                if(code.equals(day)){
                    buttonValid = "0";//允许创建考勤
                    //创建上月考勤
                    map.put("buttonInfo","创建"+lastMonth+"月份考勤");
                }
                days += listSysDict.get(i).getCode()+",";
            }else{
                days += "-";
            }

        }
        String attendDaysNotes = "每月固定（"+days.substring(0,days.length()-1)+"）号进行创建上月考勤";
        String newEmployeeDaysNotes = "每月固定（"+days.substring(0,days.length()-1)+"）允许添加新员工和员工调店";
        List<SysDict> listSysDictLastDay = this.sysDictService.getSysDictAttendAuditLastDay();
        if(listSysDictLastDay.size()>0){
            SysDict sysDict= listSysDictLastDay.get(0);
            String code = sysDict.getCode();
            List<String> codeSS = getLastDays(Integer.parseInt(code));
            for(int i = 0;i<codeSS.size();i++){
                try {
                    Date codeSSday = yyyyMMddSdf.parse(codeSS.get(i));
                    if (daySdf.format(codeSSday).equals(day)) {
                        buttonValid = "0";//允许创建考勤
                        //创建本月考勤
                        map.put("buttonInfo", "创建" + month + "月份考勤");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            attendDaysNotes +=  "，每月月末最后"+code+"日进行创建本月考勤";
            newEmployeeDaysNotes+=  "，每月月末最后"+code+"日允许添加新员工和员工调店";
        }


        map.put("buttonValid",buttonValid);

        map.put("AttendDaysNotes",attendDaysNotes);

        map.put("NewEmployeeDaysNotes",newEmployeeDaysNotes);

        Map<String,String> attendMonthMap =  getAttendMonth();
        map.put("attendMonth",attendMonthMap.get("attendMonth"));
        map.put("day",attendMonthMap.get("day"));
        map.put("time",attendMonthMap.get("time"));
        return map;
    }
    /**
     * 验证列表中的员工是否都归该督导，审核，根据手机号判断
     * @author wjk
     * @Date 2021-09-18
     */
    private boolean validationList(List<AttendAuditManagerSetResult> param,String account){
        boolean falg = true;
        //获取督导和店长拥有的店的列表
        StringBuffer shopName = new StringBuffer();
        List<AttendAuditBtyArea> list  = attendAuditBtyArchivesService.getShopListByDdPhone(account,"");
        if(list.size() == 0){
            falg = false;
        }
        for(AttendAuditBtyArea attendAuditBtyArea:list){
            shopName.append(attendAuditBtyArea.getDm());
        }
        String shopNameStr = shopName.toString();


        //大店长也可以修改，此处，根据店名，查询督导或者大店长的店，然后店名进行匹配。
        for(AttendAuditManagerSetResult attendAuditManagerSetResult : param){
            if(shopNameStr.indexOf(attendAuditManagerSetResult.getDm())<0){
                falg = false;
                break;
            }
        }
        return falg;
    }

    /**
     * 根据返回的员工列表返回不重复的提交审核的审核aaId；
     * @author wjk
     * @Date 2021-09-18
     */
    private List<Long> getAaIdListWithoutDuplicates(List<AttendAuditManagerSetResult> param){
        ArrayList<Long> aaIdList = new ArrayList<Long>();
        param.forEach(attendAuditManagerSetResult ->{
            aaIdList.add(attendAuditManagerSetResult.getAaId());
        });
        //System.out.println(aaIdList);
        List<Long> aaIdListWithoutDuplicates = aaIdList.stream().distinct().collect(Collectors.toList());
        //System.out.println(aaIdListWithoutDuplicates);
        return aaIdListWithoutDuplicates;
    }

    /**
     * 根据返回的员工列表返回不重复的提交审核的店名，店长手机号，返回考勤月份
     * @author wjk
     * @Date 2021-10-21
     */
    private List<Map<String,String>> getPushMsgListWithoutDuplicates(List<AttendAuditManagerSetResult> param){
        ArrayList<Map<String,String>> list = new ArrayList<Map<String,String>>();
        for(AttendAuditManagerSetResult attendAuditManagerSetResult: param){
            Map<String,String> map = new HashMap<String, String>();
            map.put("shopName",attendAuditManagerSetResult.getDm());
            map.put("dzMobile",attendAuditManagerSetResult.getManagerPhone());
            StringBuffer msgTime = new StringBuffer(attendAuditManagerSetResult.getAttendMonth());
            msgTime.insert(4, "年").insert(7, "月");
            map.put("msgTime",msgTime.toString());
            boolean flag = true;
            for(Map<String,String> mapShop:list){
                //若店名相等，则不进行添加
                if(mapShop.get("shopName").equals(map.get("shopName"))){
                    flag = false;
                    break;
                }
            }
            if(flag){
                list.add(map);
            }
        }
        return list;
    }

    private Serializable getKey(AttendAuditParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private AttendAudit getOldEntity(AttendAuditParam param) {
        return this.getById(getKey(param));
    }

    private AttendAudit getEntity(AttendAuditParam param) {
        AttendAudit entity = new AttendAudit();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }
    /**
     * 获取当月最后几天
     * @param days
     * @return
     */
    @Override
    public List<String> getLastDays(int days) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        List<String> list=new ArrayList<String>();
        for(int i=1;i<=days;i++){
            calendar.add(Calendar.MONTH, 1);
            calendar.set(Calendar.DATE, 1);
            calendar.add(Calendar.DATE, -i);
            Date theDate = calendar.getTime();
            String s = df.format(theDate);
            list.add(s);
        }
        return list;
    }

    /**
     * 根据店长手机号，和考勤时间，删除这家店这个月的员工信息提交信息记录
     *
     * @author wjk
     * @Date 2021-10-28
     */
    @Override
    public int deleteAttendAuditByAccount(AttendAuditDdSupervisorParam param) {
        int size = this.baseMapper.deleteAttendAuditByAccount(param);
        return size;
    }

    /**
     * 每月考勤期间，一号，二号，推送本月未考勤完成的数据到微信和小妖app
     *
     * @author wjk
     * @Date 2021-11-11
     */
    @Override
    public Map<String, String> attendAuditTimePushMsgToIMAndWx() {
        //获取考勤的月份
        Map<String,String> mapAttendMonth = attendAuditBtyArchivesService.intoAttendEmployeeMonthListValidationParam(null,null);
        String attendMonth = mapAttendMonth.get("attendMonth").replaceAll("-","");
        //查询所有人事档案中的数据，未完成，未提交，或者驳回，考勤的数据，并且考勤店长不为空的数据
        List<AttendAuditBtyAreaAuditStatusResult> list = this.baseMapper.getAttendAuditBtyAreaAuditStatusResultPushMsgToIMAndWx(attendMonth);
        StringBuffer strBf = new StringBuffer();
        int listSize = list.size();
        for(int i = 0;i<listSize;i++){
            if(ToolUtil.isNotEmpty(list.get(i).getKqDh())){
                strBf.append(list.get(i).getKqDh());
                if(i<listSize-1){
                    strBf.append(",");
                }
            }
        }
        String dzMobile = strBf.toString();
        if(ToolUtil.isNotEmpty(dzMobile)){
            //手机号为英文逗号隔开的字符串类型的值
            pushMsgService.attendAuditTimePushMsgToIM(null, dzMobile,attendMonth);
            attendAuditTimePushMsgToWx(attendMonth);
        }
        Map<String, String> map = new HashMap<String, String>();

        return map;
    }

    /**
     * （督导审核页面）督导审核，驳回，推送店长
     * @author wjk
     * @Date 2021-11-10
     */
    private void attendAuditTimePushMsgToWx(String attendMonth){
        String now = DateUtil.getNow();//当前时间
        //公众号驳回提醒：“上海崇明万达店”2021年9月考勤被督导驳回，请及时进入小妖APP，点击录入考勤菜单，在驳回列表修改并重新提交考勤
        String data = ""+attendMonth+"考勤信息还未提交，请按时填写本店考勤信息并提交督导审核";
        JSONObject tempObj = weChatSendTempMsgService.setTempParam("门店", null, "考勤提醒", "考勤提醒", now, data);



        //正式环境的推送
        if (taskConfig.getRun().equals("y")) {
            List<User> users = this.baseMapper.getUsersPushMsgToWx(attendMonth);
            if (ToolUtil.isNotEmpty(users)) {
                String[] openid = new String[users.size()];
                for(int i= 0;i<users.size();i++){
                    openid[i] = users.get(i).getOpenid();
                }
                weChatSendTempMsgService.sendmsg(openid, null, tempObj);
            }
        } else {
            //测试环境的推送
            String dzMobile = "17686420611";
            //获取受让方openid
            User user = btyWxMapper.getOpenId(dzMobile);
            String[] openid = null;
            if (ToolUtil.isNotEmpty(user)) {
                openid = new String[]{user.getOpenid()};
            }

            weChatSendTempMsgService.sendmsg(openid, null, tempObj);
        }

    }


    /**
     *
     *
     * 强制驳回数据到督导驳回状态
     * @author wjk
     * @Date 2021-11-18
     */
    @Override
    public Map<String,String> auditStatusToSubmitAudit(AttendAuditBtyAreaAuditStatusResult attendAuditBtyAreaAuditStatusResult){
        Map<String,String> map = new HashMap<String, String>();
        if(ToolUtil.isEmpty(attendAuditBtyAreaAuditStatusResult)||ToolUtil.isEmpty(attendAuditBtyAreaAuditStatusResult.getAaid())){
            map.put("size",String.valueOf("0"));
        }else{
            int size = this.baseMapper.auditStatusToSubmitAudit(attendAuditBtyAreaAuditStatusResult);
            map.put("size",String.valueOf(size));
        }
        return map;
    }
}
